from models import Ring
from models import Competitor
from models import Event
from models import EventType
from models import Level
from models import AgeGroup
from models import Gender
from models import Placing
import json
import zipfile
import tempfile
import os

expected_files = {
  'rings.json': Ring,
  'competitors.json': Competitor,
  'events.json': Event,
  'event_types.json': EventType,
  'levels.json': Level,
  'age_groups.json': AgeGroup,
  'gender.json': Gender,
  'placing.json': Placing
}

def data_import(uploaded_file):
  temp = tempfile.TemporaryFile()
  for chunk in uploaded_file.chunks():
    temp.write(chunk)
  return file_importer(temp)

def data_export():
  pass
     
def file_importer(f):
  working_dir = tempfile.mkdtemp()
  data_zip = zipfile.ZipFile(f)
  # Only extract the expected files
  for member in data_zip.namelist():
    if member in expected_files:
      data_zip.extract(working_dir)
  data_zip.close()
  for expected_file, table in expected_files.iteritems():
    if os.path.exists(os.path.join(working_dir, expected_file)):
      reader = json.reader(os.path.join(working_dir, expected_file))
      header = reader.next()
      field_names = dict([(field.name, field) for field in table._meta.fields])
      
      for item in header:
        field = field_names[item]
      
if __name__ == '__main__':
  if len(sys.argv) == 1:
    data_export()
  elif len(sys.argv) == 2:
    with open(sys.argv[1]) as f:
      file_importer(f)
  else:
    print 'Invalid arguments.  data.py zipfile.zip'